<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix"><span>更改用户资料</span><br /></div>
    <!-- 内容区放表单 -->
    <el-form label-width="80px" :model="user" :rules="abc" ref="from">
      <!-- 表单中的每一行，叫做 el-form-item -->
      <el-form-item label="登录账号">
        <el-input v-model="user.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="user.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="send">确认修改</el-button>
        <el-button @click="look">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updatedUserAPI } from '@/api/user'
export default {
  data() {
    return {
      user: { ...this.$store.state.user.user },

      // 验证规则
      abc: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '格式不正确', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    send() {
      this.$refs.from.validate(async valid => {
        if (!valid) return
        // console.log(valid)
        const { data: res } = await updatedUserAPI(this.user)
        if (res.code === 0) {
          this.$message.success(res.message)

          // 修改user里面的数据
          this.$store.dispatch('user/getUser')
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 重置表单
    look() {
      this.$refs.from.resetFields()
      this.user = { ...this.$store.state.user.user }
    }
  }
}
</script>
<style scoped>
.el-card {
  font-size: 13px;
}

.el-form {
  width: 500px;
}
</style>
